﻿// Write a program that deletes from a text file all words that start with the prefix "test". 
// Words contain only the symbols 0...9, a...z, A…Z, _.

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace _11.DeletePatternFromTextFile
{
    class DeletePatternFromTextFile
    {
        static void Main()
        {
            string path = @"..\..\";
            string inputFileName = "input.txt";
            string inputFile = Path.Combine(path, inputFileName);

            string prefix = "test";
            try
            {
                ReplaceWordWithPrefixInFile(inputFile, prefix);
                Console.WriteLine("All words with prefix '{0}...' are done.", prefix);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }

        private static void ReplaceWordWithPrefixInFile(string inputFile, string prefix)
        {
            string outputFileName = "temp.txt";
            string path = Path.GetDirectoryName(inputFile);
            string outputFile = Path.Combine(path, outputFileName);

            // pattern to match only words with prefix "test" - "test[a-z, A-Z, 0-9, _]" / word "test" does not cover this condition
            string pattern = string.Format(@"\b{0}\w{{1,}}", prefix);
            string clearDoublingIntervalPattern = @"(\s){2,}";

            using (StreamReader reader = new StreamReader(inputFile))
            using (StreamWriter writer = new StreamWriter(outputFile))
            {
                while (!reader.EndOfStream)
                {
                    string currentLine = reader.ReadLine();
                    currentLine = Regex.Replace(currentLine, pattern, String.Empty);
                    currentLine = Regex.Replace(currentLine, clearDoublingIntervalPattern, " ");
                    writer.WriteLine(currentLine);
                }
            }

            File.Replace(outputFile, inputFile, Path.ChangeExtension(inputFile, ".bak"));
        }
    }
}